package com.petter.rabbitmq.work;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;



/**
 *  Consumer :
 *  [x] Received ' Hello World!; number: 0'
 *  [x] Received ' Hello World!; number: 2'
 *  [x] Received ' Hello World!; number: 4'
 *  [x] Received ' Hello World!; number: 6'
 *  [x] Received ' Hello World!; number: 8'
 *  Consumer2 :
 *  [x] Received ' Hello World!; number: 1'
 *  [x] Received ' Hello World!; number: 3'
 *  [x] Received ' Hello World!; number: 5'
 *  [x] Received ' Hello World!; number: 7'
 *  [x] Received ' Hello World!; number: 9'
 *
 *  work 模式是公平的轮询，一个消费者进行一个消息处理，最终会达到所有的都是一样的消费次数，若消息最后轮询不完，
 *  则前面接受消息的消费者会接受到消息
 *  不会因为某个消费者消费快而进行不同的分发
 * @author : GD
 * @date :2022/3/10 : 22:11
 */
public class Producer {

    public final static String QUEUE_NAME = "workQueue";

    public static void main(String[] args) throws Exception {

        // 1. 获取链接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        // 此处用户需要有虚拟机节点权限，否则会链接报错 ,在admin -> 用户 -> set permission
//        connection error; protocol method: #method<connection.close>(reply-code=530, reply-text=NOT_ALLOWED - access to vhost '/' refused for user 'admin', class-id=10, method-id=40)
        factory.setUsername("admin");
        factory.setPassword("admin");
        // 2. 通过工厂获取连接
        Connection connection = factory.newConnection();
        // 3. 通过连接获取channel
        Channel channel = connection.createChannel();
        // 4. channel 申明declare 一个队列
//        queue – 队列的名称
//        durable - 如果我们声明一个持久队列，则为真（该队列将在服务器重新启动后继续存在）
//        exclusive - 如果我们声明一个独占队列，则为真（仅限于此连接）
//        autoDelete – 如果我们声明一个自动删除队列，则为 true（服务器将在不再使用时将其删除）
//        arguments – 队列的其他属性（构造参数）
        channel.queueDeclare(QUEUE_NAME,true,false,false,null);
        // 5. 发布对应的消息到消息队列
        String message = "Hello World!";
        for (int i = 0; i < 10; i++) {
            message = " Hello World!; number: "  +i;
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            System.out.println(" [x] Sent '" + message + "'");
        }
    }
}
